<template>
  <div class="kiki-whatsapp-ui">
    <!-- 移除静态的 order-info-container，只使用动态创建的容器 -->
    <chat-buttons 
      v-if="showButtons" 
      :chat-data="chatData" 
    />  
    <TranslateButton />
    <AiDrawer 
      v-model:visible="showTranslateDrawer" 
      @close="handleTranslateClose" 
    />
    <status-selector 
      v-if="showStatusSelector" 
      :follow-status-list="followStatusList" 
      :current-status="currentStatus" 
      @status-change="handleStatusChange" 
      ref="statusSelector"
      @close="toggleStatusSelector"
    />
    <ai-reply-alert
      v-if="showAiReplyAlert"
      :visible="showAiReplyAlert"
      :structured-data="aiReplyData"
      :chat-id="currentChatId"
      :nickname="currentChatNickname"
      @close="handleAiReplyClose"
    />
    <modify-info-dialog
      v-if="showModifyInfoDialog"
      :visible="showModifyInfoDialog"
      :chat-id="currentChatId"
      @close="handleModifyInfoClose"
      @saved="handleModifyInfoSaved"
    />
    <toast-message ref="toast" />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted, nextTick, h, render } from 'vue';
import { getChatOrderData, getFollowStatus } from '../utils/whatsappApi.js';
import { getCurrentChatId, getChatDataUnified, triggerModifyInfoDialog } from '../utils/whatsappHandler';
import { hideOrderInfoBar } from '../utils/chatDataHandler';
import ChatButtons from './ChatButtons.vue';
import StatusSelector from './StatusSelector.vue'; 
import ToastMessage from './ToastMessage.vue';
import TranslateButton from './TranslateButton.vue';
import AiDrawer from './AiDrawer.vue';
import AiReplyAlert from './AiReplyAlert.vue';
import OrderInfoBar from './OrderInfoBar.vue';
import ModifyInfoDialog from './ModifyInfoDialog.vue';

// 扩展Window接口
declare global {
  interface Window {
    statusSelectorInserted?: boolean;
    updateGlobalInfo?: Function;
    updateStatusLabelsTimer?: number;
    forceUpdateStatusLabels?: Function;
  }
}

interface StatusItem {
  label: string;
  value: string;
}

export default defineComponent({
  name: 'WhatsAppUI',
  components: {
    ChatButtons,
    StatusSelector,
    ToastMessage,
    TranslateButton,
    AiDrawer,
    AiReplyAlert,
    OrderInfoBar,
    ModifyInfoDialog
  },
  setup() {
    const chatData = ref<any>(null);
    const showButtons = ref(false);
    const showStatusSelector = ref(false);
    const followStatusList = ref<StatusItem[]>([]);
    const currentStatus = ref('');
    const toast = ref<any>(null);
    const statusSelector = ref<any>(null);
    const showTranslateDrawer = ref(false);
    
    // AI回复提醒相关状态
    const showAiReplyAlert = ref(false);
    const aiReplyData = ref<any>(null);
    const currentChatId = ref('');
    const currentChatNickname = ref('');
    
    // 修改信息对话框相关状态
    const showModifyInfoDialog = ref(false);
    
    // 获取缓存的订单数据
    const getCachedOrderData = async (chatId: string) => {
      const STORAGE_KEY_PREFIX = 'kiki_chat_order_';
      const storageKey = STORAGE_KEY_PREFIX + chatId;
      
      try {
        const result = await new Promise<{[key: string]: any}>((resolve) => {
          chrome.storage.local.get([storageKey], resolve);
        });
        
        return result[storageKey] || null;
      } catch (error) {
        console.error('获取缓存订单数据失败:', error);
        return null;
      }
    };

    // 不在这里进行调用后台接口，但是此处记得可以监控聊天对话切换的逻辑，如果有后续功能，可以添加 
    // 处理聊天变化
    const handleChatChange = async (event: CustomEvent) => {
      const chatId = event.detail?.chatId || getCurrentChatId();
      if (!chatId) {
        return;
      }
      
      // 保存当前处理的聊天ID，用于后续验证
      const processingChatId = chatId;
      
      // 添加一个标记，防止重复处理相同的聊天ID
      const processingKey = `processing-${chatId}`;
      if ((window as any)[processingKey]) {
        return;
      }

      try {
        // 设置标记，表示正在处理该聊天ID
        (window as any)[processingKey] = true;

        // 使用统一的数据获取函数
        const data = await getChatDataUnified(chatId, event.detail?.forceRefresh || false);
        
        // 在数据返回后，再次检查当前聊天ID是否仍然是我们正在处理的ID
        const currentChatIdNow = getCurrentChatId();
        if (currentChatIdNow !== processingChatId) {
          return;
        }
        
        if (data) {
          chatData.value = data;
          const status = data.follow_status || '';
          currentStatus.value = status;
          showButtons.value = true;
          currentChatId.value = chatId;
          currentChatNickname.value = data.nickname || data.name || '';
          
          // 移除 infobar 相关处理逻辑，只保留状态更新
          // MutationObserver 会负责处理 infobar 的显示
          
          // 如果存在全局更新函数，则调用它
          if (window.updateGlobalInfo && typeof window.updateGlobalInfo === 'function') {
            try {
              (window.updateGlobalInfo as Function)(status);
            } catch (error) {
              console.error('调用全局更新函数出错:', error);
            }
          }
          
          // 检查是否有 AI 回复提醒
          if (data.ChatRemind && data.ChatRemind.success && data.ChatRemind.viewed === false) {
            try {
              const current_chat_id = getCurrentChatId();
              if(current_chat_id !== chatId) {
                // 关闭
                showAiReplyAlert.value = false;
              } else {
                const structuredData = parseResponse(data.ChatRemind.content || '');
                aiReplyData.value = structuredData;
                showAiReplyAlert.value = true;
              }
            } catch (error) {
              console.error('解析 AI 回复数据出错:', error);
            }
          }
        } else {
          chatData.value = null;
          currentStatus.value = '';
        }
      } catch (error) {
        console.error('处理聊天变化出错:', error);
        toast.value?.show('获取聊天数据失败');
      } finally {
        // 清除标记
        setTimeout(() => {
          delete (window as any)[processingKey];
        }, 1000); // 1秒后清除标记，确保有足够时间完成处理
      }
    };

    // 更新状态标签
    const updateStatusLabels = (status: string) => {
      try {
        // 获取左侧列表中的当前选中项
        const selectedChat = document.querySelector('#pane-side [aria-selected="true"]');
        if (!selectedChat) return;

        // 获取联系人标题
        const titleSpan = selectedChat.querySelector('span[title]');
        if (!titleSpan) return;
        
        const titleAttr = titleSpan.getAttribute('title');
        if (!titleAttr) return;
        
        const chatTitle = titleAttr.trim();
        
        // 保存标题和状态的映射关系
        if (chatTitle && window.updateGlobalInfo && typeof window.updateGlobalInfo === 'function') {
          (window.updateGlobalInfo as Function)(status);
        }

        // 找到时间标签容器
        const timeContainer = selectedChat.querySelector('div:has(> span[aria-label])');
        if (!timeContainer) return;

        // 移除可能存在的旧状态标签
        const oldStatusLabel = timeContainer.querySelector('.kiki-status-label');
        if (oldStatusLabel) {
          oldStatusLabel.remove();
        }

        // 如果没有状态，则不添加标签
        if (!status) return;

        // 创建并添加新的状态标签
        const labelElement = document.createElement('div');
        labelElement.className = 'kiki-status-label';
        
        // 获取状态标签文本
        const statusObj = followStatusList.value.find(item => item.value === status);
        if (statusObj) {
          labelElement.textContent = statusObj.label;
          
          // 应用对应状态的颜色样式
          const colors = getStatusColors(status);
          labelElement.style.cssText = `
            display: inline-block;
            margin-left: 8px;
            padding: 2px 6px;
            background-color: ${colors.background};
            color: ${colors.text};
            border-radius: 4px;
            font-size: 12px;
            line-height: 1.2;
            vertical-align: middle;
            transition: all 0.2s ease;
          `;
          
          timeContainer.appendChild(labelElement);
        }
      } catch (error) {
        console.error('更新状态标签出错:', error);
      }
    };

    // 获取状态颜色
    const getStatusColors = (status: string) => {
      const colors: { [key: string]: { background: string, text: string } } = {
        'new': {
          background: '#e3f2fd',
          text: '#1976d2'
        },
        'converted': {
          background: '#e8f5e9',
          text: '#2e7d32'
        },
        'focus_follow': {
          background: '#004d40',
          text: '#ffffff'
        },
        'potential': {
          background: '#fff3e0',
          text: '#e65100'
        },
        'high_potential': {
          background: '#ff9800',
          text: '#ffffff'
        },
        'public_customer': {
          background: '#f5f5f5',
          text: '#616161'
        },
        'bad_customer': {
          background: '#eeeeee',
          text: '#757575'
        },
        'ai_follow': {
          background: '#f3e5f5',
          text: '#7b1fa2'
        },
        'invalid': {
          background: '#fafafa',
          text: '#9e9e9e'
        },
        'no_reply': {
          background: '#ffebee',
          text: '#c62828'
        },
        'replied': {
          background: '#e8f5e9',
          text: '#2e7d32'
        },
        'following': {
          background: '#e3f2fd',
          text: '#1976d2'
        },
        'closed': {
          background: '#f5f5f5',
          text: '#616161'
        }
      };
      
      return colors[status] || { background: '#f0f2f5', text: '#54656f' };
    };

    // 处理状态变化
    const handleStatusChange = async (newStatus: string) => {
      // 实现状态变更逻辑
      currentStatus.value = newStatus;
      toast.value?.show(`状态已更新为: ${newStatus}`);
      
      // 如果存在全局更新函数，则调用它
      if (window.updateGlobalInfo && typeof window.updateGlobalInfo === 'function') {
        try {
          (window.updateGlobalInfo as Function)(newStatus);
        } catch (error) {
          console.error('调用全局更新函数出错:', error);
        }
      }
    };

    // 初始化跟进状态列表
    const initFollowStatusList = async () => {
      try {
        const response = await getFollowStatus();
        
        if (response && response.data) {
          // 直接使用原始数据，不需要转换
          followStatusList.value = Array.isArray(response.data) ? response.data : [];
          showStatusSelector.value = true;
          
          // 在状态选择器显示后，将其移动到正确的位置
          await nextTick();
          
          // 等待 DOM 完全加载
          const waitForDom = () => {
            const titleElement = document.querySelector('div[title="对话"] h1') || 
                               document.querySelector('header h1') ||
                               document.querySelector('#app header header');
            
            if (!titleElement) {
              setTimeout(waitForDom, 1000); // 每秒检查一次
              return;
            }
            
            insertStatusSelectorToWhatsApp();
            
            // 在状态选择器插入后，尝试更新对话列表中的状态标签
            setTimeout(() => {
              updateChatListStatusLabels();
            }, 2000);
          };
          
          // 开始等待 DOM 加载
          waitForDom();
        }
      } catch (error) {
        console.error('获取跟进状态列表失败:', error);
      }
    };
    
    // 将状态选择器插入到WhatsApp界面中
    const insertStatusSelectorToWhatsApp = () => {
      if (!statusSelector.value) {
        return;
      }
      
      // 获取状态选择器元素
      const selectorElement = statusSelector.value.$el;
      if (!selectorElement) {
        console.error('无法获取状态选择器的 DOM 元素');
        return;
      }
      
      // 查找WhatsApp的标题元素 - 使用老代码中的选择器
      let titleElement = document.querySelector('div[title="对话"] h1');
      
      // 如果没有找到，尝试其他选择器
      if (!titleElement) {
        // 尝试其他可能的选择器
        const altSelectors = [
          'header h1',
          '#main header h1',
          'header span[dir="auto"]'
        ];
        
        for (const selector of altSelectors) {
          titleElement = document.querySelector(selector);
          if (titleElement) break;
        }
        
        if (!titleElement) {
          return;
        }
      }
      
      // 获取父元素
      const parentElement = titleElement.parentElement;
      if (!parentElement) {
        console.error('无法找到标题元素的父元素');
        return;
      }
      
      // 获取祖父元素（标题容器）
      const headerContainer = parentElement.parentElement;
      if (!headerContainer) {
        console.error('无法找到标题容器');
        return;
      }

      // 找到标题元素的下一个兄弟元素
      const nextSibling = parentElement.nextElementSibling;
      
      // 检查是否已经插入
      const existingSelector = document.querySelector('[data-kiki-status-selector="true"]');
      if (existingSelector && existingSelector.parentElement) {
        // 如果已经插入到正确位置，则不需要重新插入
        if (existingSelector.parentElement === headerContainer && 
            existingSelector.previousElementSibling === parentElement) {
          return;
        }
        
        // 如果在其他位置，则移除
        existingSelector.remove();
      }
      
      // 确保全局样式已添加
      if (!document.querySelector('#kiki-status-selector-styles')) {
        const style = document.createElement('style');
        style.id = 'kiki-status-selector-styles';
        style.textContent = `
          .kiki-status-selector {
            display: flex !important;
            align-items: center !important;
            padding: 12px 16px !important;
            border-bottom: 1px solid rgba(134, 150, 160, 0.15) !important;
            background-color: #fff !important;
            position: relative !important;
            z-index: 1000 !important;
            visibility: visible !important;
            opacity: 1 !important;
          }
          
          .kiki-status-select {
            width: 100% !important;
            padding: 8px !important;
            border-radius: 8px !important;
            border: 1px solid #ddd !important;
            background-color: white !important;
            font-size: 14px !important;
            outline: none !important;
            color: #333 !important;
            height: 36px !important;
            cursor: pointer !important;
            opacity: 1 !important;
          }
          
          .kiki-status-select:focus {
            border-color: #00a884 !important;
          }
          
          .kiki-status-select option {
            padding: 8px !important;
            font-size: 14px !important;
          }
          
          .kiki-add-user-button {
            padding: 6px 12px !important;
            margin-right: 10px !important;
            border: none !important;
            border-radius: 4px !important;
            background-color: #00a884 !important;
            color: white !important;
            font-size: 13px !important;
            cursor: pointer !important;
            transition: background-color 0.2s !important;
          }
          
          .kiki-add-user-button:hover {
            background-color: #008f70 !important;
          }
          
          .kiki-status-container {
            display: flex !important;
            align-items: center !important;
          }
        `;
        document.head.appendChild(style);
      }
      
      // 创建一个容器，包含"发送新消息"按钮和状态选择器
      const container = document.createElement('div');
      container.className = 'kiki-status-container';
      container.setAttribute('data-kiki-status-selector', 'true');
      
      // 创建"发送新消息"按钮
      const addUserButton = document.createElement('button');
      addUserButton.className = 'kiki-add-user-button';
      addUserButton.textContent = '加人';
      addUserButton.onclick = () => {
        // 调用 whatsappHandler.ts 中的 showAddUserDialog 函数
        // 由于无法直接调用，我们触发一个自定义事件
        const event = new CustomEvent('add-user-button-clicked');
        window.dispatchEvent(event);
      };
      
      // 将按钮和选择器添加到容器中
      container.appendChild(addUserButton);
      container.appendChild(selectorElement);
      
      // 将容器插入到标题元素后面
      try {
        if (nextSibling) {
          headerContainer.insertBefore(container, nextSibling);
        } else {
          headerContainer.appendChild(container);
        }
        
        // 设置标记
        window.statusSelectorInserted = true;
      } catch (error) {
        console.error('插入状态选择器时出错:', error);
      }
    };

    onMounted(() => {
      // 初始化跟进状态列表
      initFollowStatusList();

      // 监听聊天变化
      window.addEventListener('chat-changed', handleChatChange as unknown as EventListener);
      
      // 监听修改信息按钮点击事件
      window.addEventListener('modify-info-button-clicked', (event: Event) => {
        const customEvent = event as CustomEvent<{ chatId: string }>;
        if (customEvent.detail?.chatId) {
          currentChatId.value = customEvent.detail.chatId;
          showModifyInfoDialog.value = true;
        }
      });
      
      // 监听AI回复提醒按钮点击事件
      window.addEventListener('ai-reply-alert', (event: Event) => {
        const customEvent = event as CustomEvent<{ 
          chatId: string;
          data: any;
          nickname: string;
        }>;
        
        if (customEvent.detail?.chatId) {
          currentChatId.value = customEvent.detail.chatId;
          currentChatNickname.value = customEvent.detail.nickname;
          
          // 直接使用事件中的数据
          if (customEvent.detail.data) {
            aiReplyData.value = customEvent.detail.data;
            showAiReplyAlert.value = true;
            console.log('显示 AI 回复弹窗:', customEvent.detail.data);
          } else {
            toast.value?.show('AI回复数据为空');
          }
        }
      });
      
      // 监听AI回复弹窗关闭事件
      window.addEventListener('ai-reply-alert-close', () => {
        handleAiReplyClose();
      });
      
      // 初始触发一次聊天变化事件，使用自定义事件并包含必要信息
      const initialChatId = getCurrentChatId();
      if (initialChatId) {
        const event = new CustomEvent('chat-changed', {
          detail: { 
            chatId: initialChatId,
            forceRefresh: false // 不强制刷新，避免重复调用
          }
        });
        window.dispatchEvent(event);
      }
      
      // 监听DOM变化，确保状态选择器始终在正确位置
      // 使用防抖函数减少频繁调用
      const debounce = (fn: Function, delay: number) => {
        let timer: number | null = null;
        return function(...args: any[]) {
          if (timer) clearTimeout(timer);
          timer = window.setTimeout(() => {
            fn(...args);
            timer = null;
          }, delay);
        };
      };
      
      const debouncedInsertStatusSelector = debounce(insertStatusSelectorToWhatsApp, 500);
      const debouncedInsertTranslateButton = debounce(insertTranslateButton, 500);
      
      // 使用更长的防抖时间，避免频繁调用
      const debouncedInsertOrderInfoBar = debounce(() => {
        // 只在 DOM 变化时通过 MutationObserver 触发，不再依赖 showOrderInfoBar 状态
        const chatId = getCurrentChatId();
        if (chatId) {
          insertOrderInfoBar(chatId);
        }
      }, 800);
      
      // 监听整个文档的变化
      const observer = new MutationObserver(() => {
        // 检查标题元素和状态选择器
        const titleElement = document.querySelector('div[title="对话"] h1');
        if (titleElement && !document.querySelector('[data-kiki-status-selector="true"]')) {
          debouncedInsertStatusSelector();
        }

        // 检查输入框和翻译按钮
        const inputContainer = document.querySelector('#main div[class*="lexical-rich-text-input"]');
        if (inputContainer && !document.querySelector('.kiki-translate-wrap')) {
          debouncedInsertTranslateButton();
        }
        
        // 检查是否需要插入 OrderInfoBar
        const header = document.querySelector('#main header');
        const orderInfoContainer = document.querySelector('#main header + .order-info-container');
        const chatId = getCurrentChatId();
        
        // 只有当 header 存在且有聊天 ID 时才检查是否需要插入 OrderInfoBar
        if (header && chatId) {
          if (!orderInfoContainer || orderInfoContainer.innerHTML === '') {
            debouncedInsertOrderInfoBar();
          }
        }
      });
      
      // 开始观察文档变化
      observer.observe(document.body, { 
        childList: true, 
        subtree: true 
      });
      
      // 设置全局函数，以便可以从控制台调用
      window.forceUpdateStatusLabels = updateChatListStatusLabels;
      
      // 立即执行一次更新对话列表中的状态标签
      updateChatListStatusLabels();
      
      // 清除可能存在的旧定时器
      if (window.updateStatusLabelsTimer) {
        clearInterval(window.updateStatusLabelsTimer);
      }
      
      // 每5秒更新一次对话列表状态标签
      window.updateStatusLabelsTimer = window.setInterval(() => {
        updateChatListStatusLabels();
      }, 5000); // 5秒
      
      // 清理函数
      return () => {
        observer.disconnect();
        if (window.updateStatusLabelsTimer) {
          clearInterval(window.updateStatusLabelsTimer);
        }
      };
    });

    // 插入翻译按钮到输入框
    const insertTranslateButton = () => {
      const inputContainer = document.querySelector('#main div[class*="lexical-rich-text-input"]');
      if (!inputContainer || document.querySelector('.kiki-translate-wrap')) return;

      const translateWrap = document.createElement('div');
      translateWrap.className = 'kiki-translate-wrap';
      translateWrap.innerHTML = `
        <div class="kiki-ai-icon">AI</div>
      `;

      // 添加点击事件
      translateWrap.addEventListener('click', () => {
        showTranslateDrawer.value = true;
      });

      // 将按钮添加到输入框容器
      const textAreaContainer = inputContainer.parentElement;
      if (textAreaContainer) {
        textAreaContainer.appendChild(translateWrap);
      }

      // 添加样式
      if (!document.querySelector('#kiki-translate-button-styles')) {
        const style = document.createElement('style');
        style.id = 'kiki-translate-button-styles';
        style.textContent = `
          .kiki-translate-wrap {
            position: relative;
            display: inline-flex;
            align-items: center;
            margin-left: 8px;
            cursor: pointer;
          }

          .kiki-ai-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            background-color: #00a884;
            color: white;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            line-height: 1;
            transition: background-color 0.2s;
          }

          .kiki-ai-icon:hover {
            background-color: #008f72;
          }
        `;
        document.head.appendChild(style);
      }
    };

    // 插入 OrderInfoBar 组件到 WhatsApp 聊天对话的 header 中
    const insertOrderInfoBar = async (chatId: string) => {
      // 检查是否有其他正在进行的 OrderInfoBar 操作
      if ((window as any).orderInfoBarProcessing) {
        return;
      }
      
      // 设置处理标记
      (window as any).orderInfoBarProcessing = true;
      
      try {
        // 从本地存储获取订单数据
        const STORAGE_KEY_PREFIX = 'kiki_chat_order_';
        const storageKey = STORAGE_KEY_PREFIX + chatId;
        
        // 使用获取缓存数据的函数
        const orderData = await getCachedOrderData(chatId);
        if (!orderData || !orderData.order_no) {
          hideOrderInfoBar();
          (window as any).orderInfoBarProcessing = false;
          return;
        }
        
        const mainHeader = document.querySelector('#main header');
        if (!mainHeader) {
          (window as any).orderInfoBarProcessing = false;
          return;
        }
        
        let orderInfoContainer = document.querySelector('#main header + .order-info-container');
        
        if (!orderInfoContainer) {
          orderInfoContainer = document.createElement('div');
          orderInfoContainer.className = 'order-info-container';
          mainHeader.parentNode?.insertBefore(orderInfoContainer, mainHeader.nextSibling);
        } else {
          // 检查是否需要更新
          const currentOrderNo = orderInfoContainer.getAttribute('data-order-no');
          if (currentOrderNo === orderData.order_no && orderInfoContainer.innerHTML !== '') {
            (window as any).orderInfoBarProcessing = false;
            return;
          }
          
          orderInfoContainer.innerHTML = '';
        }
        
        // 确保容器可见
        (orderInfoContainer as HTMLElement).style.display = 'block';
        
        // 记录当前处理的订单号，用于验证数据一致性
        orderInfoContainer.setAttribute('data-order-no', orderData.order_no || '');
        // 记录当前处理的聊天ID，用于验证
        orderInfoContainer.setAttribute('data-chat-id', chatId || '');
        
        // 正确处理 remarks 数据
        let remarksData = [];
        if (orderData.remarks) {
          if (Array.isArray(orderData.remarks)) {
            remarksData = orderData.remarks;
          } else {
            // 如果不是数组，但有内容，则包装成数组
            remarksData = [orderData.remarks];
          }
        }
        
        const orderInfoBarComponent = h(OrderInfoBar, {
          orderNo: orderData.order_no,
          orderName: orderData.name,
          orderStatus: orderData.status,
          orderNote: orderData.order_note,
          orderRemark: orderData.remark || '',
          remarks: remarksData,
          createdAt: orderData.created_at,
          operationSuggestion: orderData.operation_suggestion,
          chatId: chatId,
          onClose: () => {
            // 处理关闭事件
            hideOrderInfoBar();
          },
          onFollow: () => {
            // 处理修改信息事件
            showModifyInfoDialog.value = true;
          }
        });
        
        // 渲染组件到容器中
        render(orderInfoBarComponent, orderInfoContainer);
        
        // 添加一个延迟检查，确保 OrderInfoBar 在渲染后仍然存在
        setTimeout(() => {
          const containerCheck = document.querySelector('#main header + .order-info-container');
          if (containerCheck) {
            if (containerCheck.innerHTML === '') {
              // 如果内容为空但应该显示，尝试重新渲染
              if (orderData?.order_no && getCurrentChatId() === chatId) {
                // 递归调用，但不设置处理标记，避免无限循环
                (window as any).orderInfoBarProcessing = false;
                insertOrderInfoBar(chatId);
              }
            }
          }
          
          // 清除处理标记
          (window as any).orderInfoBarProcessing = false;
        }, 300); // 300ms 后检查
      } catch (error) {
        console.error('处理 OrderInfoBar 出错:', error);
        // 确保处理标记被清除
        (window as any).orderInfoBarProcessing = false;
      }
    };

    // 更新对话列表中的状态标签
    const updateChatListStatusLabels = async () => {
      try {
        // 获取聊天标题映射
        const titleMapResult = await new Promise<any>(resolve => {
          chrome.storage.local.get(['kiki_chat_title_map'], resolve);
        });
        const titleMap = titleMapResult['kiki_chat_title_map'] || {};
        
        // if (Object.keys(titleMap).length === 0) {
        //   return;
        // }
        
        // 获取所有聊天项 - 尝试多种选择器
        let chatRows: NodeListOf<Element> = document.querySelectorAll('#pane-side [role="listitem"]');
        
        if (chatRows.length === 0) {
          // 尝试其他可能的选择器
          const selectors = [
            '[role="listitem"]',
            '#pane-side div[role="row"]',
            '#side div[role="listitem"]',
            'div[aria-label="对话列表"] div[role="listitem"]',
            'div[aria-label="Chat list"] div[role="listitem"]',
            '#pane-side > div > div > div > div'
          ];
          
          for (const selector of selectors) {
            const rows = document.querySelectorAll(selector);
            if (rows.length > 0) {
              chatRows = rows;
              break;
            }
          }
        }
        
        if (chatRows.length === 0) {
          // 尝试直接查找所有带有 title 属性的 span 元素
          const allTitleSpans = document.querySelectorAll('span[title]');
          
          if (allTitleSpans.length > 0) {
            allTitleSpans.forEach((span) => {
              const titleAttr = span.getAttribute('title');
              if (!titleAttr) return;
              
              const chatTitle = titleAttr.trim();
              const status = titleMap[chatTitle];
              
              if (!status) return;
              
              // 查找可能的时间容器 - 向上查找最近的可能容器
              let parent = span.parentElement;
              let timeContainer: Element | null = null;
              
              // 向上查找最多5层
              for (let i = 0; i < 5 && parent; i++) {
                // 查找可能包含时间的元素
                const timeSpan = parent.querySelector('span[aria-label]');
                if (timeSpan) {
                  timeContainer = parent;
                  break;
                }
                parent = parent.parentElement;
              }
              
              if (timeContainer) {
                processTimeContainer(timeContainer, status, 0);
              }
            });
            return;
          }
        }
        
        // 处理所有聊天行
        for (const row of chatRows) {
          // 获取联系人标题
          // 优先通过自定义属性获取chat_id
          const chat_id = row.getAttribute('data-kiki-chat-id');
          // console.log('updateChatListStatusLabels -> chat_id', chat_id);
          
          // 使用组件中定义的函数从本地存储获取数据
          let status = '';
          if (chat_id) {
            try {
              const orderData = await getCachedOrderData(chat_id);
              if (orderData && orderData.follow_status) { 
                status = orderData.follow_status;
                // console.log('通过本地缓存chat_id获取 -> follow_status', status);
              }
            } catch (error) {
              console.error('获取本地存储数据出错:', error);
            }
          }
          if (!status) {
            const titleSpan = row.querySelector('span[title]');
            if (!titleSpan) continue;
            
            const titleAttr = titleSpan.getAttribute('title');
            if (!titleAttr) continue;
              
            const chatTitle = titleAttr.trim();
            status = titleMap[chatTitle];
          }
      
          
          if (!status) {
            // 移除可能存在的旧状态标签
            const timeSelectors = [
              '._ak8i',
              'div:has(> span[aria-label])',
              'div > span[aria-label]',
              'div[role="gridcell"]:last-child'
            ];
            
            for (const selector of timeSelectors) {
              const container = row.querySelector(selector);
              if (container) {
                const oldStatusLabel = container.querySelector('.kiki-status-label');
                if (oldStatusLabel) {
                  oldStatusLabel.remove();
                }
              }
            }
            continue;  // 使用 continue 而不是 return，确保处理所有行
          }
          
          // 找到时间标签容器 - 尝试多种选择器
          const timeSelectors = [
            '._ak8i',
            'div:has(> span[aria-label])',
            'div > span[aria-label]',
            'div[role="gridcell"]:last-child'
          ];
          
          let timeContainer: Element | null = null;
          
          for (const selector of timeSelectors) {
            const container = row.querySelector(selector);
            if (container) {
              timeContainer = container;
              break;
            }
          }
          
          if (!timeContainer) {
            // 尝试更通用的选择器 - 查找所有 div 元素
            const divs = row.querySelectorAll('div');
            
            // 查找可能的时间容器
            divs.forEach((div) => {
              const hasTimeLabel = div.querySelector('span[aria-label]');
              if (hasTimeLabel && !timeContainer) {
                timeContainer = div;
              }
            });
            
            if (!timeContainer) {
              // 尝试使用行本身作为容器
              timeContainer = row;
            }
          }
          
          // 处理找到的容器
          if (timeContainer) {
            processTimeContainer(timeContainer, status, 0);
          }
        }
      } catch (error) {
        console.error('更新对话列表状态标签出错:', error);
      }
      
      // 处理时间容器的辅助函数
      function processTimeContainer(container: Element, status: string, index: number) {
        // 移除可能存在的旧状态标签
        const oldStatusLabel = container.querySelector('.kiki-status-label');
        if (oldStatusLabel) {
          oldStatusLabel.remove();
        }
        
        // 创建并添加新的状态标签
        const labelElement = document.createElement('div');
        labelElement.className = 'kiki-status-label';
        
        // 获取状态标签文本
        const statusObj = followStatusList.value.find(item => item.value === status);
        if (statusObj) {
          labelElement.textContent = statusObj.label;
          
          // 应用对应状态的颜色样式
          const colors = getStatusColors(status);
          
          labelElement.style.cssText = `
            display: inline-block;
            margin-left: 8px;
            padding: 2px 6px;
            background-color: ${colors.background};
            color: ${colors.text};
            border-radius: 4px;
            font-size: 12px;
            line-height: 1.2;
            vertical-align: middle;
            transition: all 0.2s ease;
            z-index: 1000;
          `;
          
          // 查找时间标签
          const timeSpan = container.querySelector('span[aria-label]');
          if (timeSpan) {
            // 将状态标签插入到时间标签前面
            timeSpan.parentElement?.insertBefore(labelElement, timeSpan);
          } else {
            // 如果找不到时间标签，则添加到容器末尾
            container.appendChild(labelElement);
          }
        }
      }
    };

    const handleTranslateClose = () => {
      showTranslateDrawer.value = false;
    };

    const handleAiReplyClose = () => {
      showAiReplyAlert.value = false;
      aiReplyData.value = null;
    };

    // 解析 AI 回复数据
    const parseResponse = (raw: string) => {
      try {
        // 提取 JSON 部分
        const jsonStart = raw.indexOf('{');
        const jsonEnd = raw.lastIndexOf('}') + 1;
        const jsonString = raw.slice(jsonStart, jsonEnd);

        // 替换 Unicode 转义字符
        const decodedString = jsonString.replace(/\\u([\d\w]{4})/gi,
          (match, grp) => String.fromCharCode(parseInt(grp, 16))
        );

        // 解析 JSON
        let structuredData = JSON.parse(decodedString);
        // 倒序
        if (structuredData['回复建议'] && Array.isArray(structuredData['回复建议'])) {
          structuredData['回复建议'] = structuredData['回复建议'].reverse();
        }
        return structuredData;
      } catch (error) {
        console.error('解析失败:', error);
        return null;
      }
    };

    // 切换状态选择器显示/隐藏
    const toggleStatusSelector = () => {
      showStatusSelector.value = !showStatusSelector.value;
    };

    // 处理订单信息栏关闭
    const handleOrderInfoClose = () => {
      // 直接调用 hideOrderInfoBar 函数
      hideOrderInfoBar();
    };

    // 处理修改信息对话框关闭
    const handleModifyInfoClose = () => {
      showModifyInfoDialog.value = false;
    };
    
    // 处理修改信息保存成功
    const handleModifyInfoSaved = async () => {
      // 重新获取聊天数据
      const chatId = currentChatId.value;
      if (chatId) {
        // 触发聊天变化事件，强制刷新数据
        const event = new CustomEvent('chat-changed', {
          detail: { 
            chatId: chatId,
            forceRefresh: true // 强制刷新
          }
        });
        window.dispatchEvent(event);
        
        // 显示成功提示
        toast.value?.show('信息已更新');
      }
    };

    return {
      chatData,
      showButtons,
      showStatusSelector,
      followStatusList,
      currentStatus,
      toast,
      statusSelector,
      showTranslateDrawer,
      handleTranslateClose,
      handleStatusChange,
      showAiReplyAlert,
      aiReplyData,
      currentChatId,
      currentChatNickname,
      handleAiReplyClose,
      toggleStatusSelector,
      handleOrderInfoClose,
      showModifyInfoDialog,
      handleModifyInfoClose,
      handleModifyInfoSaved
    };
  }
});

// 立即执行的函数，确保 updateChatListStatusLabels 被调用
(function() {
  // 在页面加载完成后执行
  window.addEventListener('load', () => {
    // 延迟 3 秒执行，确保 Vue 组件已经挂载
    setTimeout(() => {
      if (window.forceUpdateStatusLabels) {
        window.forceUpdateStatusLabels();
      } else {
        console.error('全局 forceUpdateStatusLabels 函数不存在');
      }
    }, 3000);
  });
})();
</script>

<style>
.kiki-whatsapp-ui {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  position: relative;
  z-index: 1000;
}

/* 确保 OrderInfoBar 组件能够正确显示 */
.kiki-whatsapp-ui > .order-info-bar,
#main > .order-info-bar,
#main header + .order-info-bar {
  position: relative !important;
  z-index: 1001 !important;
  margin: 0 !important;
  padding: 12px 16px !important;
  width: 100% !important;
  box-sizing: border-box !important;
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;
  background-color: #f0f8ff !important;
  border-bottom: 1px solid #d0e0f0 !important;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1) !important;
}

/* 全局样式，确保状态标签在对话列表中正确显示 */
.kiki-status-label {
  display: inline-block !important;
  margin-left: 8px !important;
  padding: 2px 6px !important;
  border-radius: 4px !important;
  font-size: 12px !important;
  line-height: 1.2 !important;
  vertical-align: middle !important;
  transition: all 0.2s ease !important;
  z-index: 1000 !important;
}

/* 添加全局样式，确保 OrderInfoBar 组件在任何位置都能正确显示 */
.order-info-bar {
  position: relative !important;
  z-index: 1001 !important;
  margin: 0 !important;
  padding: 12px 16px !important;
  width: 100% !important;
  box-sizing: border-box !important;
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;
  background-color: #f0f8ff !important;
  border-bottom: 1px solid #d0e0f0 !important;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1) !important;
}

/* 确保 OrderInfoBar 内容正确显示 */
.order-info-content {
  display: flex !important;
  justify-content: space-between !important;
  align-items: center !important;
  flex-wrap: wrap !important;
  width: 100% !important;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .order-info-content {
    flex-direction: column !important;
    align-items: flex-start !important;
  }
  
  .order-actions {
    margin-top: 12px !important;
    width: 100% !important;
    justify-content: flex-end !important;
  }
}

/* 确保按钮样式不受 WhatsApp 样式影响 */
.action-button {
  padding: 6px 12px !important;
  border: none !important;
  border-radius: 4px !important;
  background-color: #00a884 !important;
  color: white !important;
  font-size: 13px !important;
  cursor: pointer !important;
  transition: background-color 0.2s !important;
  margin: 0 4px !important;
}

.action-button:hover {
  background-color: #008f70 !important;
}
</style> 